package edu.cs.networkmonitor.scanner;

import java.util.Vector;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import edu.cs.networkmonitor.devices.PortSource;

public class PortScanner extends BaseScanner {

	private int _fromPort;
	private int _toPort;
	private String _host;
	private Vector<PortSource> _ports;

	public PortScanner(String host, int from, int to) {
		if (host == null || host.isEmpty()) {
			_host = "localhost";
		} else {
			_host = host;
		}
		_fromPort = from;
		_toPort = to;
		_ports = new Vector<PortSource>();
	}

    @Override
    public void scan() {
		ExecutorService executor = Executors.newFixedThreadPool(10);

        for (int i = _fromPort; i <= _toPort; i++) {
        	final int index = i;
            Runnable portTask = new Runnable() {
				public void run() {
		            PortSource p = new PortSource(_host, index);
					if(p.connect()){
						_ports.add(p);
					}
				}
			};
			executor.execute(portTask);
        }
	    executor.shutdown();
	    // Wait until all threads are finish
	    while (!executor.isTerminated()) {
	    }
	    System.out.println("Finished all threads");
    }

    public Object[][] getColumnData() {
        Object[][] data = new Object[_ports.size()][3];
        for (int i = 0; i < _ports.size(); i++) {
            data[i][0] = _ports.get(i).getSourceName();
            data[i][1] = _ports.get(i).getDeviceDescription();
        }
        return data;
    }
    
    public Vector<PortSource> getPorts(){
        return _ports;
    }

}
